package com.iqilu.ksd.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.RegisterStatus;
import com.iqilu.ksd.constant.SmssdkConfig;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Response;

/**
 * Created by Coofee on 2016/10/19.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    public static String TAG = "RegisterActivity";

    private static String APPKEY = SmssdkConfig.APPKEY;
    private static String APPSECRET = SmssdkConfig.APPSECRET;

    private LigDialog ligDialog;
    public String phone;
    public String password;
    public String nickname;
    public String code;
    public static int sendSmsStart = 888;
    public static int sendSmsEnd = 889;

    private ImageView btLeft;
    private TextView tvTitle;
    private EditText etTelephone;
    private EditText etVerify;
    private EditText etPassword;
    private Button btGetverify;
    private Button btSubmit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();

        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {

                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }

        };
        SMSSDK.registerEventHandler(eh);

    }


    private void initView() {
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        etTelephone = getView(R.id.et_telephone);
        etVerify = getView(R.id.et_verify);
        etPassword = getView(R.id.et_password);
        btGetverify = getView(R.id.bt_getverify);
        btSubmit = getView(R.id.bt_submit);

        tvTitle.setText(R.string.login_register);
        btLeft.setOnClickListener(this);
        btGetverify.setOnClickListener(this);
        btSubmit.setOnClickListener(this);
    }

    void getVerify() {
        phone = etTelephone.getText().toString();
        if (!matchPhone(phone)) {
            Toast.makeText(this, R.string.login_telephone_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        SMSSDK.getVerificationCode("86", phone);
        new Thread(new Runnable() {
            public int num = 60;

            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    num--;
                    Message msg = new Message();
                    msg.arg1 = num;
                    msg.arg2 = sendSmsStart;
                    if (num <= 0) {
                        msg.arg2 = sendSmsEnd;
                        handler.sendMessage(msg);
                        num = 60;
                        break;
                    } else {
                        handler.sendMessage(msg);
                    }
                }
            }
        }).start();

    }

    private void toSubmit() {
        phone = etTelephone.getText().toString();
        code = etVerify.getText().toString();
        password = etPassword.getText().toString();
        if (!matchPhone(phone)) {
            Toast.makeText(this, R.string.login_telephone_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, R.string.register_input_verify, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, R.string.login_pass_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BaseUtils.isPassword(password)) {
            Toast.makeText(this, R.string.login_pass_error, Toast.LENGTH_SHORT).show();
            return;
        }
        // 注册
        new registerThread().execute();
    }

    // 验证手机号
    public Boolean matchPhone(String phoneNum) {
        if (phoneNum.length() < 11) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) phoneNum);
        return matcher.matches();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_left:
                finish();
                break;
            case R.id.bt_getverify:
                getVerify();
                break;
            case R.id.bt_submit:
                toSubmit();
                break;
            default:
                break;
        }
    }

    class registerThread extends AsyncTask<Void, Void, Void> {

        int result = 0;
        String pushkey;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(RegisterActivity.this, getString(R.string.login_doing));
            ligDialog.show();
            nickname = phone.substring(0, 3).toString() + "*****" + phone.substring(phone.length() - 3, phone.length());
            this.pushkey = SPUtils.getPref(RegisterActivity.this, UserInfo.PUSHKEY, "");
        }

        @Override
        protected Void doInBackground(Void... voids) {
//            result = Server.Register(context, phone, password, nickname, code, pushkey);
            Response response = null;
            UserBean user = null;
            String url = Api.URL_USER + "?pushkey=" + pushkey;
            try {
                response = OkHttpUtils
                        .post()
                        .url(url)
                        .addParams("phone", "" + phone)
                        .addParams("password", "" + password)
                        .addParams("nickname", "" + nickname)
                        .addParams("code", "" + code)
                        .tag(this)
                        .build()
                        .execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    result = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (result == RegisterStatus.SUCESS) {
                try {
                    user = JSONUtils.requestDetail(response.body().string(), "data", UserBean.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (user != null && user.getId() > 0) {
                    ((MyApplication) getApplication()).setUser(user);
                    SPUtils.setPref(RegisterActivity.this, UserInfo.LOGINHASH, user.getLoginhash());
                    afterLogin();
                }

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            Log.i(TAG, "result=" + result);
            if (result == RegisterStatus.SUCESS) {
                Toast.makeText(RegisterActivity.this, R.string.register_sucess, Toast.LENGTH_SHORT).show();
                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                finish();
            } else if (result == RegisterStatus.FAIL) {
                Toast.makeText(RegisterActivity.this, R.string.register_verify_error, Toast.LENGTH_SHORT).show();
            } else if (result == RegisterStatus.HAVE_REGIST) {
                Toast.makeText(RegisterActivity.this, R.string.register_have_regist, Toast.LENGTH_SHORT).show();
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        }

    }


    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                //短信注册成功后，返回MainActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Toast.makeText(getApplicationContext(), R.string.register_verifycode_send, Toast.LENGTH_SHORT).show();
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表

                }
            } else if (result == sendSmsStart) {
                btGetverify.setEnabled(false);
                btGetverify.setText((getResources().getString(R.string.register_send_sms_again) + event));
            } else if (result == sendSmsEnd) {
                btGetverify.setEnabled(true);
                btGetverify.setText(getResources().getString(R.string.register_send_verify));
            }
        }

    };

    private void afterLogin() {
        EventBus.getDefault().post(new ChangeUserInfoEvent());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }
}